package com.example.crm.controller;

import com.example.crm.entity.Account;
import com.example.crm.entity.Shop;
import com.example.crm.service.AccountManager;
import com.example.crm.service.RedisService;
import com.example.crm.service.impl.ShopServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class ShopController {

    @Resource
    private ShopServiceImpl shopService;

    @Resource
    private AccountManager accountManager;

    @Resource
    private RedisService redisService;

    @GetMapping("/getShops")
    public ResponseEntity<List<Shop>> getData() {
        List<Shop> shops = shopService.selectShops();
        return ResponseEntity.ok(shops);
    }

    @PostMapping("/addShop")
    public ResponseEntity<String> addData(@RequestBody Shop shop) {
        //生成账号
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String liuShui = String.valueOf(redisService.getSerialNum());
        String userName = "shop_" + currentDate + "000" + liuShui;
        Account account = new Account(null, userName, "1234", null, null);
        accountManager.save(account);
        //设置accountId
        Account byUsername = accountManager.getByUsername(userName);
        shop.setAccountId(byUsername.getId());
        //自动生成店铺编码
        shop.setShopCode(userName);
        boolean save = shopService.save(shop);
        if (save) {
            return ResponseEntity.ok("Ok");
        } else {
            return ResponseEntity.ok("noOk");
        }
    }

    @PostMapping("/deleteShop")
    public ResponseEntity<String> deleteData(@RequestBody Shop shop) {
        boolean deleteShop = shopService.removeById(shop.getId());
        if (deleteShop) {
            return ResponseEntity.ok("Ok");
        } else {
            return ResponseEntity.ok("noOk");
        }
    }

    @PostMapping("/updateShop")
    public ResponseEntity<String> updateData(@RequestBody Shop shop) {
        Shop shopAccount = shopService.getById(shop.getId());
        Integer accountId = shopAccount.getAccountId();
        Account account = new Account(accountId, shop.getShopAccount(), shop.getPassword(), null, null);
        //更新店铺名称
        boolean updateShop = shopService.updateById(shop);
        //更新账号密码
        boolean updateAccount = accountManager.updateById(account);
        if (updateShop && updateAccount) {
            return ResponseEntity.ok("Ok");
        } else {
            return ResponseEntity.ok("noOk");
        }
    }

}
